﻿using Microsoft.Web.Administration;
using System;
using System.Collections.Generic;
using System.Diagnostics;
using System.Linq;
using System.Text;
using System.Threading;

namespace Forze.SharePointTray
{
    public static class IIS
    {
        private const string cw3wp = "w3wp";

        public static void Reset()
        {
            foreach (Process process in Process.GetProcessesByName(cw3wp))
            {
                process.Kill();
            }
        }

        public static void ResetPool(string applicationPool)
        {
            using (var manager = new ServerManager())
            {
                var pool = manager.ApplicationPools[applicationPool];
                if (pool != null)
                {
                    Process process = null;
                    if (pool.WorkerProcesses.Count > 0)
                    {
                        process = Process.GetProcessById(pool.WorkerProcesses[0].ProcessId);
                    }

                    if (process != null)
                    {
                        process.Kill();
                    }
                }
            }
        }

        public static void RecyclePool(string applicationPool)
        {
            //http://www.mattwrock.com/post/2011/07/28/Recycling-an-Application-Pool-with-C-(Part-2).aspx
            using (var manager = new ServerManager())
            {
                var pool = manager.ApplicationPools[applicationPool];
                if (pool != null)
                {
                    Process process = null;
                    if (pool.WorkerProcesses.Count > 0)
                    {
                        process = Process.GetProcessById(pool.WorkerProcesses[0].ProcessId);
                    }

                    pool.Recycle();
                    if (process != null)
                    {
                        while (!process.HasExited)
                        {
                            Thread.Sleep(0);
                        }

                        process.Dispose();
                    }
                }
            }
        }

    }
}
